<?php

/**
 * 
 */

/**
 * Class WAFlora
 */
Class WAFlora {

	private $data;

	function __construct( $s ) {
		$connection_string = sprintf("server=%s; database=%s; username=%s; password=%s;", $s['host'], $s['db_name'], $s['username'], $s['pass'] );
		$this->db = new MysqliDatabase($connection_string);
	}
	
	public function load_by_name ($name = '') {

		$query = sprintf('SELECT ID, TaxonSASName FROM names WHERE TaxonSASName LIKE "%s%%" GROUP BY TaxonSASName LIMIT 30;',mysql_escape_string($name));
		$this->data = $this->db->query_all($query);
		return true;
	}
	
	public function load_by_id ($id) {
		if($id=='') return false;
		$query = sprintf('SELECT * FROM `names` WHERE ID = %s',mysql_escape_string($id));
		$this->data = $this->db->query_all($query);
		return true;
	}

	public function getData() {
	
		return json_encode($this->data);
	}

	public function getDwcByIndex( $i=0 ) {
		
		$rec = $this->data[$i];

		$dwc['Family'] = $rec->Family;
		$dwc['Genus'] = $rec->Genus;
		$dwc['SpecificEpithet'] = $rec->SpeciesEpithet;
		$dwc['ScientificName'] = $rec->TaxonSASName;
		$dwc['AuthorYearOfScientificName'] = $rec->SASAuthors;
		$dwc['CatalogNumber'] = $rec->ID;
		$dwc['CatalogCode'] = 'WAF';
		$dwc['BasisOfRecord'] = 'HumanObservation';

		return( $dwc );
	}
	
	public function getNames() {
		return( $this->data );
		$data = $this->data;
		$names = $this->filterData($data['names']);
		return $names;
	}

	/**
	* Filters the search output of records without id ( 'common name' records )
	*/
	private function filterData($datum) {
		$names = array();
		if(count($datum)) {
			foreach ($datum as $data) {
				if(!is_null($data['id'])) {
					$names[] = $data;
				}
			}
		}
		return $names;
	}

	/**
	 * getTotalSpecies
	 * get Total count of distinct species (Scientific Names)
	 */
	public function getTotalSpecies () {
		$query = 'select count(DISTINCT(SpeciesEpithet)) ct FROM names';
		$res = $this->db->query_one($query);
		return $res->ct;
	}
	
}

?>